package fun.shuofeng.juc.reentranlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class TheDiningPhilosophersProblemOfReentrantLock {
    public static void main(String[] args) {
        Chopstick a = new Chopstick("A");
        Chopstick b = new Chopstick("B");
        Chopstick c = new Chopstick("C");
        Chopstick d = new Chopstick("D");
        Chopstick e = new Chopstick("E");
        new Philosopher("Tom", a, b).start();
        new Philosopher("Jack", b, c).start();
        new Philosopher("Bob", c, d).start();
        new Philosopher("Lili", d, e).start();
        new Philosopher("Ewan", e, a).start();
    }
}


class Philosopher extends Thread {

    private final Chopstick left;
    private final Chopstick right;

    public Philosopher(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true) {
            // 获取第一只筷子
            if (left.tryLock()) {
                try {
                    // 尝试获取第二只筷子
                    if (right.tryLock()) {
                        try {
                            eat();
                            think();
                        } finally {
                            right.unlock();
                        }
                    }
                } finally {
                    left.unlock();
                }
            }

        }
    }

    private void think() {
        try {
            System.out.println(this.getName() + " think...");
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private void eat() {
        System.out.println(this.getName() + " eat...");
    }
}

class Chopstick extends ReentrantLock {
    String name;

    public Chopstick(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Chopstick{" +
                "name='" + name + '\'' +
                '}';
    }
}